from fastapi import Request, status
from fastapi.exceptions import RequestValidationError, HTTPException
from fastapi.responses import JSONResponse
from app.utils.response_utils import ResponseResult
import traceback
import logging

# 配置日志记录器
logger = logging.getLogger(__name__)

def setup_exception_handlers(app):
    """为FastAPI应用设置全局异常处理器"""
    
    @app.exception_handler(RequestValidationError)
    async def validation_exception_handler(request: Request, exc: RequestValidationError):
        """处理请求验证错误"""
        logger.warning(f"请求参数验证失败: {exc.errors()}")
        return JSONResponse(
            content=ResponseResult.param_error(
                message="请求参数验证失败",
                data={"detail": exc.errors()}
            ),
            status_code=status.HTTP_400_BAD_REQUEST
        )
    
    @app.exception_handler(HTTPException)
    async def http_exception_handler(request: Request, exc: HTTPException):
        """处理HTTP异常"""
        logger.warning(f"HTTP异常: {exc.status_code} - {exc.detail}")
        
        if exc.status_code == 404:
            return JSONResponse(
                content=ResponseResult.not_found(message=exc.detail),
                status_code=exc.status_code
            )
        elif exc.status_code == 401:
            return JSONResponse(
                content=ResponseResult.unauthorized(message=exc.detail),
                status_code=exc.status_code
            )
        elif exc.status_code == 403:
            return JSONResponse(
                content=ResponseResult.forbidden(message=exc.detail),
                status_code=exc.status_code
            )
        elif exc.status_code == 400:
            return JSONResponse(
                content=ResponseResult.param_error(message=exc.detail),
                status_code=exc.status_code
            )
        else:
            return JSONResponse(
                content=ResponseResult.error(
                    code=exc.status_code,
                    message=exc.detail
                ),
                status_code=exc.status_code
            )
    
    @app.exception_handler(Exception)
    async def general_exception_handler(request: Request, exc: Exception):
        """处理所有其他异常"""
        # 记录异常详情
        error_msg = f"未处理的异常: {str(exc)}"
        logger.error(error_msg)
        logger.error(traceback.format_exc())
        
        return JSONResponse(
            content=ResponseResult.server_error(message="服务器内部错误"),
            status_code=status.HTTP_500_INTERNAL_SERVER_ERROR
        ) 